#include <QCoreApplication>
#include <QSerialPort>
#include <QElapsedTimer>
#include <QFile>
#include <QThread>
#include <iostream>
#include <string>
using namespace std;

void serialInit(QSerialPort *sp, const QString &portName, qint32 baudrate)
{
    // 设置串口名
    sp->setPortName(portName);
    // 设置波特率
    sp->setBaudRate(baudrate);
    // 设置数据位数
    sp->setDataBits(QSerialPort::Data8);
    // 设置奇偶校验
    sp->setParity(QSerialPort::NoParity);
    // 设置停止位
    sp->setStopBits(QSerialPort::OneStop);
    // 设置流控制
    sp->setFlowControl(QSerialPort::NoFlowControl);
    // 打开串口
    sp->open(QIODevice::ReadWrite);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    int portNum;
    qint32 baudrate;
    QSerialPort *serial = new QSerialPort();
    do
    {
        cout << "Serial port num:";
        cin >> portNum;
        cout << "Baud Rate:";
        cin >> baudrate;
        serialInit(serial, "COM" + QString::number(portNum), baudrate);
        if (!serial->isOpen())
            cout << "Open serial port failed" << endl;
        // 休眠 1s
        QThread::sleep(1);
    } while (!serial->isOpen());
    cout << "Open serial port success" << endl;

    // 打开测试文件 test.txt
    QFile *fp = new QFile(":/test.txt");
    if (!fp->open(QIODevice::ReadOnly))
    {
        cout << "Open file failed" << endl;
        return 0;
    }
    cout << "Open file success" << endl;

    // 打印文件大小
    int fileSize = fp->size();
    cout << "File size:" << fileSize * 8 << "bits" << endl;

    // 读取文件内容
    char *fileContent = new char[fileSize];
    fp->read(fileContent, fileSize);
    fp->close();
    cout << "Read file success" << endl;
Test:
    // 测试50次，每次延迟 1s
    QElapsedTimer timer;
    int timeSum = 0;
#define TestTimes 50
    for (int i = 0; i < TestTimes; i++)
    {
        // cout << "Test " << i + 1 << endl;

        // 开始计时
        timer.start();

        // 发送文件内容
        serial->write(fileContent, fileSize);
        serial->waitForBytesWritten(); // 等待数据发送完成A

        // 停止计时
        int time = timer.elapsed();
        cout << time << endl;
        // cout << "Time:" << time << "ms" << endl;
        //  cout << endl << "speed:" << fileSize * 8.0 * 1000  *(10.0/8.0)/ time << "bps" << endl;

        // 计算总时间
        timeSum += time;

        // 休眠 1s
        // QThread::sleep(1);
    }

    // 计算平均时间
    double timeAvg = timeSum / TestTimes;
    cout << endl
         << "Average time :" << timeAvg << "ms" << endl;
    cout << endl
         << "Average speed:" << fileSize * 8.0 * 1000 * (10.0 / 8.0) / timeAvg << "bps" << endl;

    string temp;
    cin >> temp;
    goto Test;

    return a.exec();
}
